package com.hfjava.ebook.controller;

import com.hfjava.ebook.common.JsonResult;
import com.hfjava.ebook.entity.Book;
import com.hfjava.ebook.entity.BookPageDto;
import com.hfjava.ebook.entity.Pageable;
import com.hfjava.ebook.service.BookService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    // 从前端传JSON字符串 {"cid":2,"page":1,"limit":3} 到后台,请求参数自动发生映射
    @RequestMapping(value = "/search",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult listPage(
            @RequestBody  BookPageDto bookPageDto
    ){
       Pageable pageable = bookService.findByPage(bookPageDto.getCid(),bookPageDto.getPage(),bookPageDto.getLimit());
       return JsonResult.ok(pageable);
    }


    @RequestMapping(value = "/detail/{bid}",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult bookDetail(@PathVariable(value="bid") int bid){
        Book book = bookService.findBookById(bid);
        return JsonResult.ok(book);
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public JsonResult bookAdd(@RequestBody Book book){
        int retVal = bookService.saveBook(book);
        if(retVal > 0){
            return JsonResult.success("新增电子图书信息成功！");
        }
        else {
            return JsonResult.success("新增电子图书信息失败！");
        }
    }


    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public JsonResult bookUpdate(@RequestBody Book book){
        int retVal = bookService.modifyBook(book);
        if(retVal > 0){
            return JsonResult.success("修改电子图书信息成功！");
        }
        else {
            return JsonResult.success("修改电子图书信息失败！");
        }
    }



    @RequestMapping(value = "/delete/{bid}",method = RequestMethod.GET)
    public JsonResult bookUpdate(@PathVariable(value = "bid")Integer bid){
        int retVal = bookService.deleteBookById(bid);
        if(retVal > 0){
            return JsonResult.success("删除电子图书信息成功！");
        }
        else {
            return JsonResult.success("删除电子图书信息失败！");
        }
    }

}
